package com.ruoyi.system.ali;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.common.enums.ChannelEnum;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.utils.file.AliOss;
import com.ruoyi.common.utils.sign.SignMD5Util;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.ZfbConfig;
import com.ruoyi.system.dto.ApiByPhoneAddDto;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ZfbConfigService;
import com.ruoyi.system.vo.ApiPayResultVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.TreeMap;

/**
 * 当面付
 */
@Component
public class H5PayService implements ChannelService {


    @Resource
    ISysConfigService configService;
    private static final String serverUrl = "https://openapi.alipay.com/gateway.do";
    @Resource
    private ZfbConfigService zfbConfigService;

    @Override
    public String getType() {
        return ChannelEnum.H5.getCode();
    }

    //当面付
    public Object create(AliPayDto aliPayDto, Order order) {
        order.setChannelName(ChannelEnum.H5.getName());
        order.setType("auto");
        ZfbConfig config = zfbConfigService.getChannelConfig(this.getType());
        order.setAccount(config.getAccount());
        String publicKey = config.getAlipayPublicKey();
        String privateKey = config.getPrivateKey();
//        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, config.getAppId(), privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(aliPayDto.getNotifyUtl());


        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(config.getAppId());
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(publicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");

        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("2088602262610814");
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(aliPayDto.getOrderNo());
        model.setTotalAmount(aliPayDto.getAmount().toString());
        model.setSubject("线下产品");

        model.setExtendParams(extendParams);
        //model.setProductCode("QUICK_WAP_WAY");
        request.setBizModel(model);
        AlipayTradeWapPayResponse response;
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //AlipayTradeWapPayResponse execute = alipayClient.execute(request);
            response = alipayClient.pageExecute(request);
            System.out.println(response.getBody());


        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new BusiException("渠道发生错误");
        }

        if (!response.isSuccess()) {
            throw new BusiException(response.getSubMsg());
        }
        String h5PayUrl = configService.selectConfigByKey("h5Pay") + "?orderNo=" + aliPayDto.getOrderNo();
        String projectName = configService.selectConfigByKey("projectName");
        QrConfig qrConfig = new QrConfig();
        qrConfig.setWidth(200);
        qrConfig.setHeight(200);

        byte[] bytes = QrCodeUtil.generatePng(h5PayUrl, qrConfig);
        String picUrl = AliOss.uploadToOss(bytes, projectName + "/orderReceive/" + aliPayDto.getOrderNo() + ".jpg");
//        Map<String, Object> map = new HashMap<>();
//        //移动端支付宝跳转链接
//        map.put("url", qrCode);
//        map.put("pic", picUrl);
//        map.put("amount", aliPayDto.getAmount());
//        map.put("orderNo", aliPayDto.getOrderNo());
        //        //将链接解析成二维码


        AliPayVo aliPayVo = new AliPayVo();
        aliPayVo.setOrderNo(aliPayDto.getOrderNo());
        aliPayVo.setAmount(aliPayDto.getAmount());
        aliPayVo.setPic(picUrl);
        aliPayVo.setQrCode(h5PayUrl);
        order.setHtml(response.getBody());
        order.setPic(aliPayVo.getPic());
        order.setZfbUrl(aliPayVo.getQrCode());

        ApiPayResultVo apiVo = new ApiPayResultVo();
        apiVo.setAmount(String.valueOf(order.getAmount()));
        apiVo.setOrderNo(order.getOrderNo());
        apiVo.setMerchantId(order.getMerchantId());
        TreeMap<String, String> map = SignMD5Util.objToMap(apiVo);
        String sign = SignMD5Util.getSign(map, "sign");
        String payUrl = configService.selectConfigByKey("payUrl");
        payUrl = payUrl + "?" + SignMD5Util.getStr(map, sign);
        apiVo.setUrl(payUrl);

        return apiVo;
    }

    @Override
    public AliPayVo createByPhone(ApiByPhoneAddDto apiByPhoneAddDto, Order order) {
        return null;
    }


}
